package com.example.world.dao;

import com.example.world.domain.Country;
import com.example.world.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CountryLanguageDAO {



    // 根据code查询国家
    public Country findByCode(String code) throws SQLException
    {
        // 1. 连接
        Connection conn = JDBCUtils.getConnection();
        // 2.
        String sql = "select * from country where Code=?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, code);
        // 3.
        ResultSet rs = stmt.executeQuery();
        Country c = null;

        if(rs.next())
        {
            String name = rs.getString("Name");
            int capital = rs.getInt("Capital");
            c = new Country(code,name,capital);
        }

        return c;
    }

    // 查询所有
    public List<Country> findAll() throws SQLException
    {
        // 1. 连接
        Connection conn = JDBCUtils.getConnection();
        // 2.
        String sql = "select * from country";
        PreparedStatement stmt = conn.prepareStatement(sql);
        // 3.
        ResultSet rs = stmt.executeQuery();
        List<Country> list = new ArrayList<>();
        while (rs.next())
        {
            String code = rs.getString("Code");
            String name = rs.getString("Name");
            int capital = rs.getInt("Capital");
            Country c = new Country(code, name, capital);
            list.add(c);
        }

        return list;
    }

}
